﻿namespace ContentHolder
{
    /// <summary>
    /// 树节点
    /// </summary>
    internal sealed class TrieNode
    {
        public int Index { get; set; }

        /// <summary>
        /// 叶层值
        /// </summary>
        public int Layer { get; set; }

        public bool End => this.Results != default;

        /// <summary>
        /// 当前节点值
        /// </summary>
        public char Char { get; set; }

        public List<int> Results { get; set; }

        /// <summary>
        /// 下一层映射节点
        /// </summary>
        public Dictionary<char, TrieNode> m_values { get; set; }
        public TrieNode? Failure { get; set; }

        /// <summary>
        /// 父节点
        /// </summary>
        public TrieNode? Parent { get; set; }

        /// <summary>
        /// 是否为通配符
        /// </summary>
        public bool IsWildcard { get; set; }

        /// <summary>
        /// 通配符层值
        /// </summary>
        public int WildcardLayer { get; set; }

        public bool HasWildcard { get; set; }

        public TrieNode()
        {
            Results = new List<int>();
            m_values = new Dictionary<char, TrieNode>();
        }

        /// <summary>
        /// 添加子叶节点
        /// </summary>
        /// <param name="c"></param>
        /// <returns></returns>
        public TrieNode Add(char c)
        {
            if (!m_values.TryGetValue(c, out var node))
            {
                node = new TrieNode
                {
                    Parent = this,
                    Char = c
                };
                m_values[c] = node;
            }
            return node;
        }

        public void SetResults(int index)
        {
            Results.Add(index);
        }

        /// <summary>
        /// 伪释放
        /// </summary>
        public void Dispose()
        {
            Results?.Clear();
            m_values?.Clear();
        }
    }
}
